package com.wisdom.benefit.jufa.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.collection.SparseArrayCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.widget.drawable.MColorDrawable;

/**
 * ViewPager用标题栏
 * Created by zhoudawei on 2016/12/1.
 */

public class ViewPagerTitleTabView extends LinearLayoutCompat {

    private SparseArrayCompat<String> mTitles;
    private SparseArrayCompat<View> mViews;

    private int mCurrentPosition;//当前选中位置
    private int mSelectTextColor;//选中字体颜色
    private int mNormalTextColor;//正常字体颜色
    private float mTextSize;//字体大小
    private int mTitleMargin;//标题Tab间距
    private int mTitleWidth;//标题Tab宽度
    private int mIndicatorColor;//浮标颜色
    private int mIndicatorWidth;//浮标宽度
    private int mIndicatorHeight;//浮标高度
    private int mHoverId = -1;//浮标资源
    private Bitmap mHoverBitmap;//浮标图片
    private Paint mHoverPaint;//浮标画笔

    private int mPosition;
    private float mPositionOffset;

    private onTitleTabClickListener mOnTitleTabClickListener;

    public void setNormalTextColor(int normalTextColor) {
        this.mNormalTextColor = normalTextColor;
    }

    public void setDivider(int dividerWidth) {
        mTitleMargin = dividerWidth;
        MColorDrawable colorDrawable = new MColorDrawable(Color.TRANSPARENT);
        colorDrawable.setIntrinsicWidth(dividerWidth);
        colorDrawable.setIntrinsicHeight(1);
        setDividerDrawable(colorDrawable);
        setShowDividers(SHOW_DIVIDER_MIDDLE);
    }

    public void setHoverBitmap(@DrawableRes int hoverId) {
        mHoverId = hoverId;
        mHoverBitmap = BitmapFactory.decodeResource(getResources(), hoverId);
        postInvalidate();
    }

    public void setOnTitleTabClickListener(onTitleTabClickListener onTitleTabClickListener) {
        mOnTitleTabClickListener = onTitleTabClickListener;
    }

    public void setViewPager(@NonNull ViewPager viewPager) {
        viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                mPosition = position;
                mPositionOffset = positionOffset;
                postInvalidate();
            }

            @Override
            public void onPageSelected(int position) {
                mCurrentPosition = position;
                updateTitleTextColor(mCurrentPosition);
            }
        });
    }

    public ViewPagerTitleTabView(Context context) {
        this(context, null);
    }

    public ViewPagerTitleTabView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ViewPagerTitleTabView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ViewPagerTitleTabView, defStyleAttr, 0);
        mSelectTextColor = array.getColor(R.styleable.ViewPagerTitleTabView_selectTextColor,
                ContextCompat.getColor(context, R.color.blue_3586f9));
        mNormalTextColor = array.getColor(R.styleable.ViewPagerTitleTabView_normalTextColor,
                ContextCompat.getColor(context, R.color.black_333333));
        mTextSize = array.getDimension(R.styleable.ViewPagerTitleTabView_textSize,
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16, dm));
        mTitleMargin = (int) array.getDimension(R.styleable.ViewPagerTitleTabView_titleMargin,
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, dm));
        mTitleWidth = (int) array.getDimension(R.styleable.ViewPagerTitleTabView_titleWidth,
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, dm));
        mIndicatorColor = array.getColor(R.styleable.ViewPagerTitleTabView_indicatorColor,
                ContextCompat.getColor(context, R.color.blue_3586f9));
        mIndicatorWidth = (int) array.getDimension(R.styleable.ViewPagerTitleTabView_indicatorWidth,
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 50, dm));
        mIndicatorHeight = (int) array.getDimension(R.styleable.ViewPagerTitleTabView_indicatorHeight,
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, dm));
        array.recycle();
        setOrientation(HORIZONTAL);
        setDivider(mTitleMargin);
        setWillNotDraw(false);
        init();
    }

    private void init() {
        mTitles = new SparseArrayCompat<>();
        mViews = new SparseArrayCompat<>();
        if (mHoverId != -1) {
            mHoverBitmap = BitmapFactory.decodeResource(getResources(), mHoverId);
        } else {
            mHoverBitmap = Bitmap.createBitmap(mIndicatorWidth, mIndicatorHeight, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(mHoverBitmap);
            canvas.drawColor(mIndicatorColor);
        }
        mHoverPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    }

    public void setTitles(String[] titles) {
        if (titles == null)
            return;
        mTitles.clear();
        for (int i = 0; i < titles.length; i++) {
            mTitles.put(i, titles[i]);
        }
        initTitleViews();
    }

    private void initTitleViews() {
        removeAllViews();
        mViews.clear();
        for (int i = 0; i < mTitles.size(); i++) {
            AppCompatTextView textView = initTitleTextView(mTitles.get(i));
            mViews.put(i, textView);
            addView(textView, i);
        }
        updateTitleTextColor(mCurrentPosition);
    }

    private AppCompatTextView initTitleTextView(String title) {
        final AppCompatTextView textView = new AppCompatTextView(getContext());
        textView.setText(title);
        LayoutParams lp = new LayoutParams(mTitleWidth, ViewGroup.LayoutParams.MATCH_PARENT);
        textView.setLayoutParams(lp);
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize);
        textView.setOnClickListener(v -> {
            mCurrentPosition = mViews.indexOfValue(textView);
            updateTitleTextColor(mCurrentPosition);
            if (mOnTitleTabClickListener != null) {
                mOnTitleTabClickListener.onTitleTabClick(textView, mCurrentPosition);
            }
        });
        return textView;
    }

    private void updateTitleTextColor(int currentPosition) {
        for (int i = 0; i < mViews.size(); i++) {
            AppCompatTextView view = (AppCompatTextView) mViews.get(i);
            if (view != null) {
                if (currentPosition == i)
                    view.setTextColor(mSelectTextColor);
                else
                    view.setTextColor(mNormalTextColor);
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawHover(canvas);
    }

    private Rect dst;

    private void drawHover(Canvas canvas) {
        if (dst == null)
            dst = new Rect();
        final int hoverWidth = mIndicatorWidth;
        final int left = (int) (getPaddingStart() + 1.0f * (hoverWidth + mTitleMargin) * (mPosition + mPositionOffset));
        dst.set(left, getHeight() - mIndicatorHeight, left + hoverWidth, getHeight());
        canvas.drawBitmap(mHoverBitmap, null, dst, mHoverPaint);
    }

    public SparseArrayCompat<View> getViews() {
        return mViews;
    }

    public int getTitleWidth() {
        return mTitleWidth;
    }

    public interface onTitleTabClickListener {
        void onTitleTabClick(View view, int position);
    }
}
